package com.lanou3g.farmdoctor.stream;

import com.google.gson.Gson;
import com.lanou3g.farmdoctor.application.FDApplication;
import com.lanou3g.farmdoctor.utils.CloseHelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 本类由: Risky 创建于: 15/11/24.
 */
public class ReadStream<T> {

    private Class<T> clazz;
    private int resId;
    private Gson gson;
    private String response;

    public ReadStream(Class<T> clazz, int resId) {
        this.clazz = clazz;
        this.gson = new Gson();
        response = openResource(resId);
    }

    private String openResource(int resId) {

        InputStream is = FDApplication.getContext().getResources().openRawResource(resId);
        StringBuffer sb = new StringBuffer();

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String str = "";
        byte[] buffer = new byte[1024];

        try {
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            CloseHelper.close(is);
            CloseHelper.close(br);
        }
        return null;
    }

    private T _getEntity() {
        T t = gson.fromJson(response, clazz);
        return t;
    }

    public static <VT> VT getEntity(Class<VT> clazz, int resId) {
        ReadStream<VT> rs = new ReadStream<>(clazz, resId);
        VT vt = rs._getEntity();
        return vt;
    }

}
